package com.example.k12.dialog

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import com.example.k12.R
import com.example.k12.base.BaseDialog
import com.example.k12.databinding.DialogContentBinding
import androidx.core.graphics.toColorInt
import com.bumptech.glide.Glide
import com.example.k12.utlis.CircleTransform

class InputPhoneDialog(
    context: Context,
    private val bitmap: Bitmap? = null,
    private val callback: (String) -> Unit
) :
    BaseDialog<DialogContentBinding>(context) {
    override fun getWidth(): Int = context.resources.getDimensionPixelSize(R.dimen.dialog_width)

    override fun initData() {

        Glide.with(context)
            .asBitmap()
            .load(bitmap)
            .centerCrop()
            .transform(CircleTransform())
            .into(mBinding.ivUser)

        val text = "绑定家长手机号后4位"
        val spannableString = SpannableString(text)
        val start = text.indexOf("后4位")
        val end = start + 3
        spannableString.setSpan(
            ForegroundColorSpan("#1aad19".toColorInt()),
            start,
            end,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        mBinding.tvHint.text = spannableString

        // 绑定数字按键点击事件
        val buttons = mapOf(
            mBinding.btn1 to "1", mBinding.btn2 to "2", mBinding.btn3 to "3",
            mBinding.btn4 to "4", mBinding.btn5 to "5", mBinding.btn6 to "6",
            mBinding.btn7 to "7", mBinding.btn8 to "8", mBinding.btn9 to "9",
            mBinding.btn0 to "0"
        )
        for ((btn, digit) in buttons) {
            btn.setOnClickListener {
                inputDigit(digit)
            }
        }
        mBinding.btnDelete.setOnClickListener {
            deleteLastDigit()
        }
    }

    private fun inputDigit(digit: String) {
        if (mBinding.etDigit1.text.isEmpty()) {
            mBinding.etDigit1.setText(digit)
        } else if (mBinding.etDigit2.text.isEmpty()) {
            mBinding.etDigit2.setText(digit)
        } else if (mBinding.etDigit3.text.isEmpty()) {
            mBinding.etDigit3.setText(digit)
        } else if (mBinding.etDigit4.text.isEmpty()) {
            mBinding.etDigit4.setText(digit)
            callback(mBinding.etDigit1.text.toString() + mBinding.etDigit2.text.toString() + mBinding.etDigit3.text.toString() + mBinding.etDigit4.text.toString())
            dismiss()
        }
    }

    private fun deleteLastDigit() {
        if (!mBinding.etDigit4.text.isEmpty()) {
            mBinding.etDigit4.setText("")
        } else if (!mBinding.etDigit3.text.isEmpty()) {
            mBinding.etDigit3.setText("")
        } else if (!mBinding.etDigit2.text.isEmpty()) {
            mBinding.etDigit2.setText("")
        } else if (!mBinding.etDigit1.text.isEmpty()) {
            mBinding.etDigit1.setText("")
        }
    }
}